package leetcode.code1802;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public int maxValue(int n, int index, int maxSum) {
		long L = index + 1, R = n - index;
		long l = 1, r = maxSum;
		long ans = 0;
		while (l <= r) {
			long mid = l + ((r - l) >> 1);
			long total = sum(L, R, mid);
			if (total <= maxSum) {
				ans = mid;
				l = mid + 1;
			} else {
				r = mid - 1;
			}
		}
		return (int) ans;
	}

	private long sum(long L, long R, long mid) {
		return this.sum(L, mid) + this.sum(R, mid) - mid;
	}

	private long sum(long L, long mid) {
		return mid >= L ? ((mid - L + 1) + mid) * L / 2 : (1 + mid) * mid / 2 + L - mid;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(3, this.maxValue(6, 1, 10));
		HelpDebug.compare(2, this.maxValue(4, 2, 6));
		HelpDebug.compare(31621, this.maxValue(123456, 34754, 1000000000));

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
